import { HttpClient } from '@angular/common/http';
import { Component, ElementRef, ViewChild } from '@angular/core';
import { HotTableComponent, HotTableModule } from '@handsontable/angular';
import Handsontable from 'handsontable';

@Component({
  selector: 'app-home',
  standalone: true,
  imports: [HotTableModule],
  templateUrl: './home.component.html',
  styleUrl: './home.component.scss'
})
export class HomeComponent {

  @ViewChild('hotTable', { static: false })
  hotTable!: HotTableComponent;

  count = 0;

  hotSettings: Handsontable.GridSettings = {
    data: [],
    colHeaders: [],
    rowHeaders: true,
    height: 800,
    rowHeights: 50, // 行高
    colWidths: 100, // 列宽
    wordWrap: false, // 是否换行
    persistentState: true,
    manualColumnResize: true, // 是否表头修改列宽
    manualColumnMove: true,
    contextMenu: true,
    columnSorting: true, // 列排序
    licenseKey: "non-commercial-and-evaluation"
  }

  hotSettings2: Handsontable.GridSettings = {
    data: [],
    colHeaders: [],
    rowHeaders: true,
    height: 800,
    rowHeights: 50, // 行高
    colWidths: 100, // 列宽
    wordWrap: false, // 是否换行
    // persistentState: true,
    manualColumnResize: true, // 是否表头修改列宽
    manualColumnMove: true,
    contextMenu: true,
    columnSorting: true, // 列排序
    licenseKey: "non-commercial-and-evaluation"
  }

  constructor(
    public http: HttpClient,
    public el: ElementRef
  ) { }

  ngAfterViewInit() {
    this.getData();
  }

  getData() {
    const url2 = '/assets/mock/data.json'
    this.http.get(url2).subscribe((res: any) => {
      if (Number(res.code) === 1) {
        const list = res.data;
        this.count = res.count || 0;
        if (list.length > 0) {
          // ng写法（部分配置不生效）
          this.hotTable.updateHotTable({
            data: list,
            colHeaders: Object.keys(list[0])
          });

          // 普通写法（使用原生dom初始化）
          this.hotSettings2.data = list;
          this.hotSettings2.colHeaders = Object.keys(list[0]);
          const hotTable2 = this.el.nativeElement.querySelector('#hotTable2');
          const plugin2 = new Handsontable(hotTable2, this.hotSettings);
          plugin2.updateSettings(this.hotSettings2);
        }
        console.log(res)
      } else {
        console.log('接口异常')
      }
    }, () => {
      console.log('网络异常');
    })
  }
}
